using QxFramework.Core;
using QxFramework.Utilities;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using UnityEngine.SceneManagement;
using Random = UnityEngine.Random;
using System.Reflection;
using System.IO;
using System.Globalization;

namespace QxFramework.Core
{
    public class Data : Singleton<Data>,ISystemModule
    {
        public float TimeSize = 1;

        private readonly string userName = "User0";

     //   private readonly string fileName = "Data";
        public string UserName
        {
            get
            {
                return userName;
            }
        }

        #region 游戏数据存取接口

        private readonly GameDataContainer _gameDataContainer = new GameDataContainer();

        /// <summary>
        /// 取得游戏数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <returns></returns>
        public T Get<T>(DataType dataType) where T : GameDataBase, new()
        {
            return _gameDataContainer.Get<T>(dataType.ToString());
        }

        /// <summary>
        /// 初始化游戏数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="data"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public bool InitData<T>(out T data,DataType dataType) where T : GameDataBase, new()
        {
            return _gameDataContainer.InitData<T>(out data, dataType.ToString());
        }

        /// <summary>
        /// 设置被修改
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="action"></param>
        /// <param name="key"></param>
        public void SetModify<T>(T t, object modifier,DataType dataType)
            where T : GameDataBase, new()
        {
            _gameDataContainer.SetModify<T>(t, modifier, dataType.ToString() );
        }

        /// <summary>
        /// 注册更新监听
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="action"></param>
        /// <param name="key"></param>
        public void RegisterUpdateListener<T>(Action<GameDataBase> action,DataType dataType)
            where T : GameDataBase, new()
        {
            _gameDataContainer.RegisterUpdateListener<T>(action, dataType.ToString());
        }

        /// <summary>
        /// 消除有关某个对象的所有监听
        /// </summary>
        /// <typeparam name="T">类型</typeparam>
        /// <param name="obj">添加过监听的对象</param>
        public void RemoveAbout(object obj)
        {
            _gameDataContainer.RemoveAbout(obj);
        }

     //   [HideInInspector]
     //   public int CurrentMap = 0;

        /// <summary>
        /// 获取所有注册的数据
        /// </summary>
        /// <returns></returns>
        public Dictionary<string, Dictionary<Type, GameDataContainer.SavedGameData>> GetAllData()
        {
            return _gameDataContainer.GetAll();
        }

    //    public void SaveToFile(string FileName)
        public void SaveToFile()
        {
            /*if (FileName == "")
            {
                return;
            }*/
            var json = _gameDataContainer.ToSaveJson();
         //   Debug.Log(Application.persistentDataPath + "/" + FileName);
            File.WriteAllText(Application.persistentDataPath+"/" +userName+".json",json);
        }

        //public void LoadFromFile(string FileName)
        public void LoadFromFile()
        {
            if (File.Exists(Application.persistentDataPath + "/" + userName + ".json") == false)
            {
                _gameDataContainer.Clear();
                return;
            }
            try
            {
                var json = File.ReadAllText(Application.persistentDataPath + "/" + userName + ".json");
                _gameDataContainer.FromSaveJson(json);
            //    LoadLevel(FileName);
            }
            catch (Exception e)
            {
                Debug.LogWarning("OpenUI有bug,需要修复");
                UIManager.Instance.Open("DialogWindowUI", 0, args: new DialogWindowUI.DialogWindowUIArg
                ("警告", "存档已损坏或不兼容最新版本", null, "确定", () => { }));
                Debug.LogError(userName + ".json");
                return;
            }
        }
        /// <summary>
        /// 清除关于某一类型的数据并存档
        /// </summary>
        /// <param name="dataType"></param>
        public void ClearDataTypeAndSave(DataType dataType)
        {
            _gameDataContainer.RemoveDataAbout(dataType.ToString());
            SaveToFile();
        }
        /// <summary>
        /// 检查数据中是否存在某一类型的数据
        /// </summary>
        /// <param name="dataType"></param>
        /// <returns></returns>
        public bool CheckIfDataTypeExist(DataType dataType)
        {
            return _gameDataContainer.CheckIfKeyExist(dataType.ToString());
        }
        public void DeleteFile(string FileName)
        {
            File.Delete(Application.persistentDataPath + "/" + FileName);
        }
        /*
        /// <summary>
        /// 加载关卡的逻辑放在这里
        /// </summary>
        /// <returns></returns>
        public void LoadLevel(string FileName)
        {
            ProcedureManager.Instance.ChangeTo(Launcher.Instance.StartProcedure);
        }
        */

        #endregion 游戏数据存取接口

        #region 变量的声明和初始化
        #endregion 变量的声明和初始化

        #region 读表类函数,基层轮子

        private readonly TableAgent _tableAgent = new TableAgent();

        public TableAgent Table
        {
            get { return _tableAgent; }
        }

        public void SetTableAgent()
        {
            var list = ResourceManager.Instance.LoadAll<TextAsset>("Text/Table/");
            for (int i = 0; i < list.Length; i++)
            {
                _tableAgent.Add(list[i].text);
            }
        }

        public override void Initialize()
        {
            //    throw new NotImplementedException();
            SetTableAgent();
            //LoadFromFile();
        }

        public void Update(float deltaTime)
        {
         //   throw new NotImplementedException();
        }

        public void FixedUpdate(float deltaTime)
        {
       //     throw new NotImplementedException();
        }

        public void Dispose()
        {
        //    throw new NotImplementedException();
        }

        #endregion 读表类函数,基层轮子

        #region 胜利失败的监听

        #endregion 胜利失败的监听

        /*        /// <summary>
                /// 临时翻译，后面转为表格
                /// </summary>
                /// <param name="item"></param>
                /// <returns></returns>
                public bool Translate(string item, out string des)
                {
                    try
                    {
                        des = TableAgent.GetString("Description", item, "Name");
                        return !des.Equals("");
                    }
                    catch (Exception)
                    {
                        des = item;
                        return false;
                    }
                }*/
    }
}